package com.yht.weblog.admin.event.subscriber;

import com.yht.weblog.admin.event.ReadArticleEvent;
import com.yht.weblog.common.domain.mapper.ArticleMapper;
import com.yht.weblog.common.domain.mapper.StatisticsArticlePVMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.time.LocalDate;

/**
 * @author: yht
 * @date: 2024/1/25 0:00
 * @description:
 **/
@Component
@Slf4j
public class ReadArticleSubscriber implements ApplicationListener<ReadArticleEvent> {

    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private StatisticsArticlePVMapper articlePVMapper;

    /**
     * 文章阅读消费成功后，更新文章阅读量
     *
     * @param event 文章阅读事件
     */
    @Override
    @Async("threadPoolTaskExecutor")
    public void onApplicationEvent(ReadArticleEvent event) {
        // 获取文章ID
        Long articleId = event.getArticleId();

        // 获取当前线程名称
        String threadName = Thread.currentThread().getName();

        // 记录日志，输出当前线程名称
        log.info("==> 线程名称: {}", threadName);
        // 记录日志，输出文章阅读消费成功的消息和文章ID
        log.info("==> 文章阅读消费成功，articleId: {}", articleId);
        // 更新文章阅读量
        articleMapper.increaseReadNum(articleId);
        log.info("==> 更新文章阅读量成功，articleId: {}", articleId);

        LocalDate currDate = LocalDate.now();
        articlePVMapper.increasePVCount(currDate);
        log.info("==> 更新 PV 访问量成功，pvDate: {}", currDate);
    }

}
